//
//  QLMEvaluationVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/23.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMEvaluationVC.h"
#import "QLMEvaluationCell.h"

@interface QLMEvaluationVC ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,CWStarRateViewDelegate,QLMEvaluationCellDelegate>{
    NSArray *titleArr;
    QLMEvaluationCell *evaluationCell;
    UITableView *_otableview;
    NSMutableArray *btnArray;
    
    QLMPlaceholderTextView *extraTextview;
    NSString *customerEvaluationNumber;
    
    NSString *isClear;
    NSString *isWorker;
    NSString *isHour;
    UIButton *commitButton;
}

@end

@implementation QLMEvaluationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"服务评价";
    
    btnArray=[NSMutableArray array];
    titleArr=[NSArray arrayWithObjects:@"工作人员是否穿工作服",@"是否维修完清理现场",@"是否24小时内处理完毕",@"用户评价",@"备注", nil];
    
    CGFloat extraH=40;
    if (!_canEditeBool) {
        extraH=0;
    }
    
    CGRect rect=CGRectMake(0, 10, kScreen_width, kScreen_height-10-extraH-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight);
    _otableview=[[UITableView alloc] initWithFrame:rect style:UITableViewStyleGrouped];
    _otableview.backgroundColor=[UIColor clearColor];
    _otableview.delegate=self;
    _otableview.dataSource=self;
    _otableview.bounces=NO;
    _otableview.scrollEnabled=NO;
    _otableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _otableview.showsVerticalScrollIndicator=NO;
    _otableview.showsHorizontalScrollIndicator=NO;
    _otableview.tableFooterView=[UIView new];
    [self.view addSubview:_otableview];
    
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = CGRectMake(0, kScreen_height-40-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight, kScreen_width, 40);
    [newButton setTitle:@"提交" forState:UIControlStateNormal];
    [newButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    newButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
    newButton.backgroundColor=kButtonColor;
    [newButton addTarget:self action:@selector(commitBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:newButton];
    
    commitButton=newButton;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    
    if (_canEditeBool) {
        commitButton.hidden=NO;
    }else{
        commitButton.hidden=YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
- (void)commitBtnAction:(UIButton *)sender{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSString *userid=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }

    if (isClear.length==0) {
        ETToast(@"请选择是否维修完清理现场！");
        return;
    }
    if (isWorker.length==0) {
        ETToast(@"请选择工作人员是否穿工作服！");
        return;
    }
    if (isHour.length==0) {
        ETToast(@"请选择是否24小时内处理完毕！");
        return;
    }
    if (customerEvaluationNumber.length==0) {
        ETToast(@"请选择服务星级！");
        return;
    }
    if (extraTextview.text.length==0||[extraTextview.text isEqualToString:@"请写下您的意见"]) {
        ETToast(@"请写下您的意见");
        return;
    }
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:_orderListInfoModel.receiverMaintenanceId forKey:@"maintenanceId"];
    [paramerDic setObject:extraTextview.text forKey:@"evaluationContext"];
    [paramerDic setObject:customerEvaluationNumber forKey:@"customerEvaluationNumber"];
    [paramerDic setObject:_orderListInfoModel.repairOrderId forKey:@"repairOrderId"];
    [paramerDic setObject:userid forKey:@"userId"];
    [paramerDic setObject:isClear forKey:@"isClear"];
    [paramerDic setObject:isWorker forKey:@"isWorker"];
    [paramerDic setObject:isHour forKey:@"isHour"];
    [paramerDic setObject:_serviceStart forKey:@"serviceStart"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPathAndFormData:@"/rest/maintenance/save" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            [self.navigationController popViewControllerAnimated:YES];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - QLMEvaluationCellDelegate
- (void)tapBtnAction:(NSInteger)itemTag{
    switch (itemTag) {
        case 101:
            [self _setButtonImage:101 WithOtherBtnTag:102];
            break;
        case 102:
            [self _setButtonImage:102 WithOtherBtnTag:101];
            break;
        case 203:
            [self _setButtonImage:203 WithOtherBtnTag:204];
            break;
        case 204:
            [self _setButtonImage:204 WithOtherBtnTag:203];
            break;
        case 305:
            [self _setButtonImage:305 WithOtherBtnTag:306];
            break;
        case 306:
            [self _setButtonImage:306 WithOtherBtnTag:305];
            break;
        default:
            break;
    }
}

- (void)_setButtonImage:(NSInteger)btnTag WithOtherBtnTag:(NSInteger)otherTag{
    
    NSInteger aRow = btnTag%100-1;
    NSInteger tmpRow=otherTag%100-1;
    
    if (aRow==0) {
        isWorker=@"1";
    }else if (aRow==1){
        isWorker=@"0";
    }else if (aRow==2){
        isClear=@"1";
    }else if (aRow==3){
        isClear=@"0";
    }else if (aRow==4){
        isHour=@"1";
    }else if (aRow==5){
        isHour=@"0";
    }
    
    UIButton *tmpTrBtn=(UIButton *)btnArray[aRow];
    UIButton *tmpFaBtn=(UIButton *)btnArray[tmpRow];;
    [self changeButton:tmpTrBtn unselBtn:tmpFaBtn];
}

- (void)changeButton:(UIButton *)btn unselBtn:(UIButton *)unBtn{
    [btn setImage:[UIImage imageNamed:@"btn_dyes"] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithRed:1.00 green:0.70 blue:0.00 alpha:1.00] forState:UIControlStateNormal];
    
    [unBtn setImage:[UIImage imageNamed:@"name_uns"] forState:UIControlStateNormal];
    [unBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
}

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor whiteColor];
    
    NSArray *titArr=[NSArray arrayWithObjects:@"您的每次评价都是对我们最大的鼓励",@"写下您的意见帮助我们进步", nil];
    
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    newButton.frame = CGRectMake(0, 0, kScreen_width, 44);
    [newButton setTitle:titArr[section] forState:UIControlStateNormal];
    [newButton setTitleColor:UIColorFromRGB(0x9a9a9a) forState:UIControlStateNormal];
    newButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
    [headerView addSubview:newButton];
    
    UIImageView *lineImageView=[[UIImageView alloc] initWithFrame:CGRectMake(10, 42, kScreen_width-20, 2)];
    lineImageView.image=[UIImage imageNamed:@"fengexian_1"];
    [headerView addSubview:lineImageView];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 125;
    }
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section!=0) {
        return nil;
    }
    
    UIView *footerView=[[UIView alloc] init];
    footerView.backgroundColor=[UIColor clearColor];
    
    UIView *backV=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 120)];
    backV.backgroundColor=[UIColor whiteColor];
    backV.userInteractionEnabled=YES;
    [footerView addSubview:backV];
    
    UIImageView *lineImageView=[[UIImageView alloc] initWithFrame:CGRectMake(10, 0, kScreen_width-20, 1)];
    lineImageView.image=[UIImage imageNamed:@"fengex_2"];
    [backV addSubview:lineImageView];
    
    UILabel *_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 12, kScreen_width-40, 30)];
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.font = [UIFont systemFontOfSize:18.0f];
    _titleLabel.textColor = UIColorFromRGB(0x6b6b6b);
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.text=@"满意度评分";
    [backV addSubview:_titleLabel];
    
    CWStarRateView *starRateView1=[[CWStarRateView alloc] initWithFrame:CGRectMake(50,60,kScreen_width-100,30) numberOfStars:5];
    
    if (_canEditeBool) {
        starRateView1.userInteractionEnabled=YES;
        starRateView1.scorePercent = 0;
    }else{
        starRateView1.userInteractionEnabled=NO;
        starRateView1.scorePercent=[_evaluInfoModel.customerEvaluationNumber floatValue]/5;
    }
    starRateView1.allowIncompleteStar = NO;
    starRateView1.hasAnimation = YES;
    starRateView1.delegate=self;
    starRateView1.backgroundColor=[UIColor clearColor];
    [backV addSubview:starRateView1];
    
    return footerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        return 120;
    }
    return 44*3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    evaluationCell=[QLMEvaluationCell cellWithTableView:tableView AtIndexPath:indexPath];
    evaluationCell.selectionStyle=UITableViewCellSelectionStyleNone;
    evaluationCell.delegate=self;
    
    if (indexPath.section==0) {
    
        [btnArray addObject:evaluationCell.ture1Btn];
        [btnArray addObject:evaluationCell.false1Btn];
        [btnArray addObject:evaluationCell.ture2Btn];
        [btnArray addObject:evaluationCell.false2Btn];
        [btnArray addObject:evaluationCell.ture3Btn];
        [btnArray addObject:evaluationCell.false3Btn];

        for (UIButton *btn in btnArray) {
            if (_canEditeBool) {
                btn.enabled=YES;
            }else{
                btn.enabled=NO;
            }
        }
        
        if (!_canEditeBool) {
            
            if ([_evaluInfoModel.isWorker integerValue]==1) {
                [self changeButton:evaluationCell.ture1Btn unselBtn:evaluationCell.false1Btn];
            }else if ([_evaluInfoModel.isWorker integerValue]==0) {
                [self changeButton:evaluationCell.false1Btn unselBtn:evaluationCell.ture1Btn];
            }
            
            if ([_evaluInfoModel.isClear integerValue]==1) {
                [self changeButton:evaluationCell.ture2Btn unselBtn:evaluationCell.false2Btn];
            }else if ([_evaluInfoModel.isClear integerValue]==0) {
                [self changeButton:evaluationCell.false2Btn unselBtn:evaluationCell.ture2Btn];
            }
            
            if ([_evaluInfoModel.isHour integerValue]==1) {
                [self changeButton:evaluationCell.ture3Btn unselBtn:evaluationCell.false3Btn];
            }else if ([_evaluInfoModel.isHour integerValue]==0) {
                [self changeButton:evaluationCell.false3Btn unselBtn:evaluationCell.ture3Btn];
            }
            
        }else{
            
//            [self tapBtnAction:101];
//            [self tapBtnAction:203];
//            [self tapBtnAction:305];
        }

    }else if (indexPath.section==1) {
        extraTextview=[[QLMPlaceholderTextView alloc] initWithFrame:CGRectMake(10, 10, kScreen_width-20, 100)];
        extraTextview.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
        
        if (_canEditeBool) {
            extraTextview.editable=YES;
            extraTextview.placeholder=@"请写下您的意见";
        }else{
            extraTextview.editable=NO;
            extraTextview.text=_evaluInfoModel.evaluationContext;
        }
        extraTextview.delegate=self;
        extraTextview.textColor=[UIColor darkGrayColor];
        extraTextview.layer.masksToBounds=YES;
        extraTextview.layer.cornerRadius=8;
        [evaluationCell addSubview:extraTextview];
    }
    
    return evaluationCell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)starRateView:(CWStarRateView *)starRateView scroePercentDidChange:(CGFloat)newScorePercent{
    customerEvaluationNumber=[NSString stringWithFormat:@"%.f",newScorePercent];
}

@end
